# coding:utf-8
import configparser
import json
import os
import time

from selenium import webdriver

user_pswd_cfg = os.environ['user_pswd']
cf = configparser.ConfigParser()
cf.read(user_pswd_cfg, encoding="utf-8")
qq_user = cf.get('qq', 'qq_user')
qq_pswd = cf.get('qq', 'qq_pswd')


class Douyu(object):
    def __init__(self):
        # 构建url
        # 构建浏览器驱动
        # 发起请求
        self.url = 'https://www.douyu.com/directory/all'
        self.driver = webdriver.Chrome(executable_path=r"C:/Users/lz/SeleniumEngine/Chrome/2.43/chromedriver")
        self.file = open('./ext/cSelenium/douyu.json', 'w', encoding='utf-8')

    def parse_data(self):
        # 获取房间节点列表
        node_list = self.driver.find_elements_by_xpath('//*[@id="live-list-contentbox"]/li/a')
        print(len(node_list))
        data_list = []
        for node in node_list:
            temp = {}
            temp['title'] = node.find_element_by_xpath('./div/div/h3').text
            temp['type'] = node.find_element_by_xpath('./div/div/span').text
            temp['owner'] = node.find_element_by_xpath('./div/p/span[1]').text
            temp['views'] = node.find_element_by_xpath('./div/p/span[2]').text
            temp['cover'] = node.find_element_by_xpath('./span/img').get_attribute('data-original')
            temp['url'] = node.get_attribute('href')
            data_list.append(temp)
        return data_list

    def save_data(self, data_list):
        for data in data_list:
            str_data = json.dumps(data, ensure_ascii=False) + ',\n'
            self.file.write(str_data)

    def __del__(self):
        self.driver.close()
        self.file.close()

    def run(self):
        self.driver.get(self.url)
        while True:
            # 解析数据
            data_list = self.parse_data()
            # 保存数据
            self.save_data(data_list)
            # 点击下一页
            try:
                el_next = self.driver.find_element_by_xpath('//a[@class="shark-pager-next"]')
                el_next.click()
                time.sleep(3)
                break
            except:
                break


class SeleniumDemo:
    def _test_driver(self):
        """
        sd = SeleniumDemo()
        sd._test_driver()
        """
        # 创建浏览器对象
        # driver = webdriver.edge()
        # driver = webdriver.firefox()
        # driver = webdriver.ie()
        # driver = webdriver.safari()
        # driver = webdriver.android()
        # driver = webdriver.PhantomJS()
        driver = webdriver.Chrome(executable_path=r"C:/Users/lz/SeleniumEngine/Chrome/2.43/chromedriver")
        print(driver)

    def _test_response(self):
        """
        sd = SeleniumDemo()
        sd._test_response()
        """
        # 获取url对应的响应
        driver = webdriver.Chrome(executable_path=r"C:/Users/lz/SeleniumEngine/Chrome/2.43/chromedriver")
        driver.get('http://www.baidu.com')

    def _test_save_screenshot(self):
        """
        sd = SeleniumDemo()
        sd._test_save_screenshot()
        """
        # 保存快照
        driver = webdriver.Chrome(executable_path=r"C:/Users/lz/SeleniumEngine/Chrome/2.43/chromedriver")
        driver.get('http://www.baidu.com')
        driver.save_screenshot('./ext/cSelenium/baidu.png')

    def _test_input(self):
        """
        sd = SeleniumDemo()
        sd._test_input()
        """
        # 定位到输入框
        driver = webdriver.Chrome(executable_path=r"C:/Users/lz/SeleniumEngine/Chrome/2.43/chromedriver")
        driver.get('http://www.baidu.com')
        el = driver.find_element_by_id('kw')
        # el = driver.find_element_by_xpath('//*[@id="kw"]')
        # el = driver.find_element_by_css_selector('#kw')
        # el = driver.find_element_by_name('wd')
        # el = driver.find_element_by_xpath('//*[@id="u1"]/a[2]')
        el.click()
        print(el.text, el.get_attribute('href'))
        print(el)
        el.send_keys('Hello')
        el.click()

    def _test_page_source(self):
        """
        sd = SeleniumDemo()
        sd._test_page_source()
        """
        # 打印源码
        driver = webdriver.Chrome(executable_path=r"C:/Users/lz/SeleniumEngine/Chrome/2.43/chromedriver")
        driver.get('http://www.baidu.com')
        time.sleep(3)
        print(driver.page_source)

    def _test_cookies(self):
        """
        sd = SeleniumDemo()
        sd._test_cookies()
        """
        # 打印 cookies
        driver = webdriver.Chrome(executable_path=r"C:/Users/lz/SeleniumEngine/Chrome/2.43/chromedriver")
        driver.get('http://www.baidu.com')
        print(driver.get_cookies())

    def _test_title(self):
        """
        sd = SeleniumDemo()
        sd._test_title()
        """
        # 打印标题
        driver = webdriver.Chrome(executable_path=r"C:/Users/lz/SeleniumEngine/Chrome/2.43/chromedriver")
        driver.get('http://www.baidu.com')
        print(driver.title)

    def _test_current_url(self):
        """
        sd = SeleniumDemo()
        sd._test_current_url()
        """
        # 打印当前 url
        driver = webdriver.Chrome(executable_path=r"C:/Users/lz/SeleniumEngine/Chrome/2.43/chromedriver")
        driver.get('http://www.baidu.com')
        print(driver.current_url)

    def _test_close(self):
        """
        sd = SeleniumDemo()
        sd._test_close()
        """
        driver = webdriver.Chrome(executable_path=r"C:/Users/lz/SeleniumEngine/Chrome/2.43/chromedriver")
        driver.get('http://www.baidu.com')
        # driver.close()
        driver.quit()

    def _test_window(self):
        """
        sd = SeleniumDemo()
        sd._test_window()
        """
        url = 'http://sh.58.com'
        driver = webdriver.Chrome(executable_path=r"C:/Users/lz/SeleniumEngine/Chrome/2.43/chromedriver")
        driver.get(url)
        # 定位到房屋出租元素，点击元素
        el = driver.find_element_by_xpath('//div[@class="colWrap"]/div[1]/div[1]/span[1]/a')
        el.click()

        # 打印url
        print(driver.current_url)

        # 查看所有的标签列表
        window_list = driver.window_handles
        print(window_list)

        # 切换列表
        driver.switch_to.window(window_list[1])
        print(driver.current_url)
        driver.quit()

    def _test_frame(self):
        """
        sd = SeleniumDemo()
        sd._test_frame()
        """
        # 构建url
        url = 'https://qzone.qq.com/'
        # 构建浏览器驱动
        driver = webdriver.Chrome(executable_path=r"C:/Users/lz/SeleniumEngine/Chrome/2.43/chromedriver")
        # 访问登录界面
        driver.get(url)
        time.sleep(3)
        # 框架需要先进入，再在里面进行元素定位
        el_iframe = driver.find_element_by_xpath('//*[@id="login_frame"]')
        # 进入框架
        driver.switch_to.frame(el_iframe)
        # 点击账号密码登录(获取到节点，调用模拟点击)
        el = driver.find_element_by_xpath('//*[@id="switcher_plogin"]')
        print(el.text)
        el.click()
        time.sleep(2)
        # 输入账号
        el_user = driver.find_element_by_xpath('//*[@id="u"]')
        el_user.send_keys(qq_user)
        # 输入密码
        el_pwd = driver.find_element_by_xpath('//*[@id="p"]')
        el_pwd.send_keys(qq_pswd)
        # 点击登陆
        el_sub = driver.find_element_by_xpath('//*[@id="login_button"]')
        el_sub.click()
        time.sleep(2)
        el_sub.click()

    def _test_douyu(self):
        """
        sd = SeleniumDemo()
        sd._test_douyu()
        """
        douyu = Douyu()
        douyu.run()

    def _test_execute_script(self):
        """
        sd = SeleniumDemo()
        sd._test_execute_script()
        """
        # 打开浏览器
        driver = webdriver.Chrome(executable_path=r"C:/Users/lz/SeleniumEngine/Chrome/2.43/chromedriver")
        driver.get('http://www.baidu.com')
        print(driver.get_cookies())

        # 输入查询关键字
        time.sleep(3)
        kw = driver.find_element_by_id('kw')
        kw.send_keys('hello')
        kw.click()

        # 点击一条链接
        time.sleep(3)
        a = driver.find_element_by_xpath('//*[@id="4"]/h3/a')
        a.click()

        # 切换到新窗口，弹框
        time.sleep(3)
        window_list = driver.window_handles
        driver.switch_to.window(window_list[1])
        driver.execute_script('alert($("#1 h3 a").html());')

        time.sleep(3)
        driver.close()


if __name__ == '__main__':
    sd = SeleniumDemo()
    sd._test_execute_script()